<template>
  <div id="app">
    <el-row :gutter="20">
      <!-- 左侧编辑器，占50% -->
      <el-col :span="12">
        <editor
          api-key="q0067g07wq9mo8ykgah7cngwkffdyi4elqnxkw9ztz0wq6jr"
          :init="{
            height: 800,
            language: 'zh_CN',
            menubar: false,
            plugins: [
              'advlist autolink lists link image charmap print preview anchor',
              'searchreplace visualblocks code fullscreen',
              'insertdatetime media table paste code help wordcount'
            ],
            toolbar: [
              'undo redo | cut copy paste pastetext | selectall | codesample code | searchreplace visualblocks fullscreen preview print',
              'bold italic underline strikethrough subscript superscript | forecolor backcolor | removeformat',
              'fontselect fontsizeselect formatselect',
              'alignleft aligncenter alignright alignjustify | outdent indent | bullist numlist | checklist',
              'link unlink anchor image media | insertVariable',
              'table tabledelete | tableprops tablerowprops tablecellprops | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol'
            ],
            fontsize_formats: '8px 10px 12px 14px 16px 18px 24px 36px',
            content_style: `
              body { font-family:Helvetica,Arial,sans-serif; font-size:14px }
              [contenteditable='true'] { cursor: text; }
              span.variable-text {
                cursor: pointer !important;
                color: #409EFF !important;
                padding: 0 2px;
                background-color: rgba(64, 158, 255, 0.05);
                border-radius: 3px;
                display: inline-block;
              }
              span.variable-text:hover {
                text-decoration: underline !important;
                background-color: rgba(64, 158, 255, 0.1) !important;
              }
            `,
            setup: function(editor) {
              editor.ui.registry.addButton('insertVariable', {
                text: '插入变量',
                onAction: () => {
                  const content = '<span class=\'variable-text\' data-variable=\'true\' title=\'姓名\'>[[name]]</span>';
                  editor.insertContent(content);
                }
              });
            }
          }"
          v-model="content"
          @input="handleEditorChange"
        />
      </el-col>

      <!-- 右侧预览区域，占50% -->
      <el-col :span="12">
        <div class="preview-container">
          <div class="preview-header">
            <h3 class="preview-title">预览区域</h3>
          </div>
          <div class="preview-body">
            <div class="preview-content">
              <div v-for="(segment, index) in processedSegments" :key="index" class="preview-segment">
                <span v-if="segment.type === 'text'" v-html="segment.content"></span>
                <template v-else-if="segment.type === 'variable'">
                  <div class="variable-input-wrapper">
                    <label v-if="segment.label" class="variable-label">{{ segment.label }}：</label>
                    <el-input
                      v-model="dataMap[segment.index].value"
                      :type="dataMap[segment.index].controlType"
                      :placeholder="dataMap[segment.index].dataName"
                      class="variable-input"
                    />
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <div class="action-footer">
      <el-button @click="cancelAction">取 消</el-button>
      <el-button :loading="loading" type="primary" @click="addAction">确 定</el-button>
    </div>
  </div>
</template>

<script>
import Editor from '@tinymce/tinymce-vue';

export default {
  name: 'App',
  components: {
    Editor
  },
  data() {
    return {
      content: '这是一个示例文本，包含变量 [[name]] 和 [[age]]',
      loading: false,
      dataMap: [
        {
          dataKey: 'name',
          dataName: '姓名',
          value: '',
          controlType: 'text'
        },
        {
          dataKey: 'age',
          dataName: '年龄',
          value: '',
          controlType: 'number'
        }
      ]
    };
  },
  computed: {
    processedSegments() {
      const segments = [];
      const content = this.content;
      let lastIndex = 0;
      const regex = /\[\[(.*?)\]\]/g;
      let match;

      while ((match = regex.exec(content)) !== null) {
        // 添加变量前的文本
        if (match.index > lastIndex) {
          const textContent = content.slice(lastIndex, match.index);
          if (textContent.trim()) {
            segments.push({
              type: 'text',
              content: this.processHtml(textContent)
            });
          }
        }

        // 处理变量
        const variableKey = match[1];
        const variableIndex = this.dataMap.findIndex(item => item.dataKey === variableKey);

        if (variableIndex !== -1) {
          segments.push({
            type: 'variable',
            index: variableIndex,
            label: this.dataMap[variableIndex].dataName
          });
        } else {
          segments.push({
            type: 'text',
            content: match[0]
          });
        }

        lastIndex = match.index + match[0].length;
      }

      // 添加剩余文本
      if (lastIndex < content.length) {
        const remainingText = content.slice(lastIndex);
        if (remainingText.trim()) {
          segments.push({
            type: 'text',
            content: this.processHtml(remainingText)
          });
        }
      }

      return segments;
    }
  },
  methods: {
    processHtml(text) {
      // 保留HTML标签，但转换换行符为<br>
      return text.replace(/\n/g, '<br>');
    },
    handleEditorChange(value) {
      this.content = value;
    },
    addAction() {
      const variables = {};
      this.dataMap.forEach(item => {
        variables[item.dataKey] = item.value;
      });
      console.log('编辑器内容:', this.content);
      console.log('变量值:', variables);
    },
    cancelAction() {
      this.content = '';
      this.dataMap.forEach(item => {
        item.value = '';
      });
    }
  }
};
</script>

<style>
.preview-container {
  height: 800px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.preview-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.preview-title {
  color: #333;
  font-size: 16px;
  font-weight: bold;
  margin: 0;
}

.preview-body {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.preview-content {
  line-height: 1.6;
}

.preview-segment {
  display: inline;
}

.preview-segment span {
  white-space: pre-wrap;
}

.variable-input-wrapper {
  display: inline-flex;
  align-items: center;
  margin: 0 4px;
  vertical-align: middle;
}

.variable-label {
  margin-right: 8px;
  color: #606266;
  font-size: 14px;
}

.variable-input {
  width: 200px;
}

.variable-input.el-input {
  margin: 0;
}

.action-footer {
  margin-top: 20px;
  text-align: center;
}

/* 确保输入框内的文本垂直居中 */
.el-input__inner {
  line-height: 32px;
}
</style>
